package com.marui.mianshi.thread.lock;

import com.marui.mianshi.thread.util.CustomThreadPool;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author marui
 * @date 2020/4/15 9:59
 * @since 1.0
 * 死锁演示
 */
public class DeadLock {
    private String lockA = "lockA";
    private String lockB = "lockB";

    public void getOne() throws InterruptedException {
        synchronized (lockA){
            System.out.println(Thread.currentThread().getName()+"试图获取lockB");
            TimeUnit.SECONDS.sleep(1);
            synchronized (lockB){
                System.out.println("getOne 得到资源");
            }
        }
    }


    public void getTwo() throws InterruptedException {
        synchronized (lockB){
            System.out.println(Thread.currentThread().getName()+"试图获取lockA");
            TimeUnit.SECONDS.sleep(1);
            synchronized (lockA){
                System.out.println("getTwo 得到资源");
            }
        }
    }


    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = CustomThreadPool.customThreadPool();
        DeadLock deadLock = new DeadLock();
        try {
            threadPoolExecutor.execute(()->{
                try {
                    deadLock.getOne();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });

            threadPoolExecutor.execute(()->{
                try {
                    deadLock.getTwo();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        } finally {
                threadPoolExecutor.shutdown();
        }

    }

}
